import { Directive, DirectiveBinding } from 'vue';

let observer = null

export const lazyLoad: Directive = {
    mounted(el: HTMLElement, binding: DirectiveBinding) {
        const options = {
            root: null,
            rootMargin: '0px',
            threshold: 0.1 // 当元素10%可见时触发
        };
        observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    binding.value(); // 当元素进入视口时，调用传入的回调函数
                }
            });
        }, options);

        observer.observe(el)
    },
    unmounted(el: HTMLElement) {
        observer.unobserve(el); // 停止观察
    }
};